package com.farewell.hotel.service.impl;

import com.farewell.hotel.entity.InfoSearch;
import com.farewell.hotel.mapper.UserAuthorityMapper;
import com.farewell.hotel.mapper.UserMapper;
import com.farewell.hotel.pojo.User;
import com.farewell.hotel.service.UserService;
import com.farewell.hotel.utils.MD5Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Farewell
 * @date 2021/4/21
 */
@Service("UserService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserAuthorityMapper userAuthorityMapper;

    @Override
    public User findByPwd(String username, String pwd) {
        // md5加密
        try {
            String md5Pwd = MD5Tool.md5(pwd);
            return userMapper.findByPwd(username, md5Pwd);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<User> findSystemUserByLimit(InfoSearch userInfoSearch) {
        return userMapper.findSystemUserByLimit(userInfoSearch);
    }

    @Override
    public void updateSystemUserStatus(Long userId, Boolean flag) {
        userMapper.updateSystemUserStatus(userId, flag);
    }

    @Override
    public void addSystemUser(User user) {
        try {
            user.setPwd(MD5Tool.md5(user.getPwd()));
            userMapper.addSystemUser(user);
            User afterAddUser = userMapper.findByPwd(user.getUsername(), user.getPwd());
            String oneIds = user.getOneIds();
            String[] oneIdsList = oneIds.split(",");
            for (String s : oneIdsList) {
                userAuthorityMapper.addUserAndAuthority(afterAddUser.getId(), Long.parseLong(s));
            }
            String twoIds = user.getTwoIds();
            String[] twoIdsList = twoIds.split(",");
            for (String s : twoIdsList) {
                userAuthorityMapper.addUserAndAuthority(afterAddUser.getId(), Long.parseLong(s));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteSystemUser(Long userId) {
        userMapper.deleteSystemUser(userId);
    }
}
